/**
 * 账号留资情况统计
 * - 使用自定义封装组件，简化代码，统一管理。
 * - 2025-07-14 12:06:33 tzj
 * */
import React, {useState} from "react"
// import BaseComponent from "../../components/BaseComponent";
import withBasePage from "../../components/BaseComponent/withBasePage";
import {mrhzApi} from "../../services/basic";
import StopModal from "./stopModal";
import {Button, Col, Tooltip} from "antd";
import Utils from "../../utils";
// import {SearchOutlined} from "@ant-design/icons";
import "./style.css"
import {InfoCircleOutlined} from "@ant-design/icons";

// 要显示的form表单
const formItemList =
    [
        "companies",
        {
            name: "dateRange",
            label:'留资日期',
            start: "qsrq",
            end: "jsrq"
        }];
// 显示的按钮
const buttons = ["query", "export",];

const kzcbRrender = (_, record) => {
    return (record.kz && record.kz !== "0") ? Utils.formatNumber(Number(record.statcost) / Number(record.kz)) : 0
}

const lzcbRender = (_, record) => {
    return (record.zlz && record.zlz !== "0") ? Utils.formatNumber(Number(record.statcost) / Number(record.zlz)) : 0
}

const lzzhlRender = (_, record) => {
    if (record.kz && record.zlz && record.kz !== "0" && record.zlz !== "0") {
        return Utils.formatNumber(record.zlz * 100 / record.kz)
    }
    return 0;
}

const txt = (a, b, record, suffix = false) => {
    if (!record.children) return a;
    const bNum = Number(b)
    const bTxt = '（' + bNum + (suffix ? '%' : '') + '）'
    const spanB = bNum > 0 ? <span className='red'>{bTxt}</span> : bNum < 0 ?
        <span className='green'>{bTxt}</span> : bTxt
    return <>{a} {spanB}</>
}

// 表格列信息
const columns = [
    {
        title: '账号名称 / 计划名称',
        dataIndex: 'zhmc',
        sumName: "合计"
    },
    {
        title: '消耗',
        dataIndex: 'statcost',
        sorter: (a, b) => a.statcost - b.statcost,
        excelRender: text => text,
        render: (val, record) => txt(val, record.fdxhs, record)
    },
    {
        title: '客资',
        dataIndex: 'kz',
        sorter: (a, b) => a.kz - b.kz,
        excelRender: text => text,
        render: (val, record) => txt(val, record.fdkzs, record)
    },
    {
        title: '客资成本',
        dataIndex: 'kzcb',
        // render: kzcbRrender,
        render: (val, record) => txt(kzcbRrender(val, record), record.fdkzdj, record),
        sorter: (a, b) => kzcbRrender(0, a) - kzcbRrender(0, b),
        excelRender: kzcbRrender,
        // sorter: true,
        numFmt: "0.00",
        formula: "=IFERROR({{statcost}}/{{kz}}, 0)",
    },
    {
        title: '总留资',
        dataIndex: 'zlz',
        sorter: (a, b) => a.zlz - b.zlz,
        excelRender: text => text,
        render: (val, record) => txt(val, record.fdlzs, record)
    },
    {
        title: '留资成本',
        dataIndex: 'lzcb',
        // render: lzcbRender,
        // sorter: true,
        numFmt: "0.00",
        formula: "=IFERROR({{statcost}}/{{zlz}}, 0)",

        render: (val, record) => txt(lzcbRender(val, record), record.fdlzdj, record),
        sorter: (a, b) => lzcbRender(0, a) - lzcbRender(0, b),
        excelRender: lzcbRender,
    },
    {
        title: '留资转换率(%)',
        dataIndex: 'lzzhl',
        sorter: (a, b) => lzzhlRender(0, a) - lzzhlRender(0, b),
        numFmt: "0.00%",
        formula: "=IFERROR({{zlz}}/{{kz}}, 0)",
        excelRender: (val, record) => lzzhlRender(val, record),
        render: (val, record) => txt(lzzhlRender(val, record), record.fdzhl, record, true)
    },
    {
        title: '其他公司数量',
        dataIndex: 'qtsl',
        sorter: true,
    },
    {
        title: '无效数量',
        dataIndex: 'wxsl',
        sorter: true,
    },
    {
        title: '拍摄数量',
        dataIndex: 'pssl',
        sorter: true,
    },
    {
        title: '直播时长(h)',
        dataIndex: 'sc',
        sorter: true,
    },
]

// 实际执行还是在class里，而非视为function
const modalRef = React.createRef()

const StopBtn = ({self}) => {
    const btnClick = () => {
        modalRef.current && modalRef.current.open(self.state.dataList);
    }
    return (<Col span={2}>
        <Button
            // icon={<SearchOutlined/>}
            onClick={btnClick}
            className="search-button">
            截止
        </Button>
    </Col>)
}

const dataProcess = (arr) => {
    const map = new Map();
    arr.forEach(item => {

        /*  根据账号进行分组  */
        const obj = {
            ...item,
            zhmc: item.jhmc
        }
        const obj2 = {
            ...obj,
            // 拍摄数量
            pssl: null,
            // (直播)时长
            sc: null,
            // // 浮动消耗数
            // fdxhs:null,
            // // 浮动客资数
            // fdkzs:null,
            // // 浮动留资数
            // fdlzs:null,
            // // 浮动转换率
            // fdzhl:null,
        }
        // if (item.jhid) {
        if (map.has(item.zhmc)) {
            const existing = map.get(item.zhmc);
            existing.children.push(obj2)
            existing.statcost = Utils.addPrecise(existing.statcost, item.statcost)
            existing.kz += Number(item.kz)
            existing.zlz += Number(item.zlz)
            // existing.lzcb = Utils.addPrecise(existing.lzcb, Number(item.lzcb))
            existing.qtsl += Number(item.qtsl)
            existing.wxsl += Number(item.wxsl)
            // existing.pssl += Number(item.pssl)
            // existing.sc = Utils.addPrecise(existing.sc, Number(item.sc))
        } else {
            map.set(item.zhmc, {
                zhmc: item.zhmc,
                children: [obj2],
                statcost: Number(item.statcost),
                kz: Number(item.kz),
                zlz: Number(item.zlz),
                // lzcb: Number(item.lzcb),
                qtsl: Number(item.qtsl),
                wxsl: Number(item.wxsl),
                pssl: Number(item.pssl),
                sc: Number(item.sc),
                fdxhs: Number(item.fdxhs),
                fdkzs: Number(item.fdkzs),
                fdlzs: Number(item.fdlzs),
                fdzhl: Number(item.fdzhl),
                fdkzdj: Number(item.fdkzdj),
                fdlzdj: Number(item.fdlzdj),
            })
        }
        // }
    })
    // map.forEach(item => {
    //     item.lzzhl = item.kz ? Utils.formatNumber(item.zlz * 100 / item.kz) : 0
    // })
    // 转换Map为数组并添加层级key
    const list = Array.from(map.values()).map((parent, parentIndex) => {
        const parentKey = (parentIndex + 1).toString();

        // 为子项添加层级key
        const childrenWithKeys = parent.children.map((child, childIndex) => ({
            ...child,
            key: `${parentKey}-${childIndex + 1}`
        }));

        return {
            ...parent,
            key: parentKey,
            children: childrenWithKeys
        };
    });
    console.log(list)
    return list
}

export default withBasePage({
    state: {
        formItemList,
        buttons,
        // columns,
        filename: "账号留资情况统计",
        queryAll: true,
        sumRow: true,
        btnOther: [StopBtn],
        expandable: {
            expandRowByClick: true,
            rowExpandable: (record) => !!record.children, // 可选：控制哪些行可以展开
        },
        // 隐藏排序提示语
        hideSortTooltip: false,
    },
    columns: columns,
    queryApi: mrhzApi.getPagezh,
    hasLzModal: true,
    onRowDoubleClick(record) {
        if (record.children) return
        const params = {
            ...this.form.dataForm,
            sfzh: record.zhbh,
            jhid: record.jhid,
        }
        params.zzrq = params.jsrq;
        delete params.jsrq;

        const config = {
            // key: "zhmc",
            // val: record.zhmc,
            // label: "账号名称",
        }
        this.lzModalRef.open(params, config);
    },
    dataProcess,
    // extraContentBeforeTable: (hoc) => <StopBtn hoc={hoc}/>,
    extraContentAfterTable: () => <StopModal ref={modalRef}></StopModal>,
})(() => null);